package org.example.bazhouzuoye.model;

import java.sql.*;

public class DBTest {
    String username, password;
    public void getLoginInfo(String username, String password) {
        this.username=username;
        this.password=password;
    }

   public void userlogin() {
        String url = "https://gitee.com/lin-sanzz/7-2.git";
        String user = "root";
        String password = "060516";
        Connection con=null;
        PreparedStatement ps=null;
        ResultSet resultSet=null;
        int id=0;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            con = DriverManager.getConnection(url, user, password);
            System.out.println(con);

            //开始搬运数据
            //con.createStatement();更安全,容易出sql注入bug
            //con.prepareStatement();更便捷,不容易出sql注入bug
            String sql="select * from user where username=? and password=?";
            ps=con.prepareStatement(sql);
            ps.setString(1,"admin");
            ps.setString(2,"123456");
            resultSet=ps.executeQuery();
            while(resultSet.next()){
                id=resultSet.getInt("id");//字段的名称或者序号
                System.out.println(resultSet.getString("username"));
                System.out.println(resultSet.getString("email"));

            }



        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        finally {//后开的先关
            if (con != null) {
                try {
                    con.close();
                    System.out.println("数据库连接已关闭。");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                    System.out.println("数据库连接已关闭。");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (resultSet != null) {
                try {
                    resultSet.close();
                    System.out.println("数据库连接已关闭。");
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}